package q712_minimumDeleteSum;

public class Solution {
    /*
    和72题 编辑距离 实际上相同
    本质就是动态规划过程中 字符串从哪个方向变化过来 所需要减的字符ASCII最少
    所以只需要考虑从dp[i][j - 1]和dp[i - 1][j]两个方向
    如果当前的两个字符相等 则直接dp[i][j] = dp[i - 1][j - 1];
     */
    public int minimumDeleteSum(String s1, String s2) {
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];
        for (int i = 1; i <= s1.length(); ++i) {
            dp[i][0] += dp[i - 1][0] + s1.charAt(i - 1);
        }

        for (int i = 1; i <= s2.length(); ++i) {
            dp[0][i] += dp[0][i - 1] + s2.charAt(i - 1);
        }

        for (int i = 1; i <= s1.length(); ++i) {
            for (int j = 1; j <= s2.length(); ++j) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i][j - 1] + s2.charAt(j - 1), dp[i - 1][j] + s1.charAt(i - 1));
                }
            }
        }

        return dp[s1.length()][s2.length()];
    }
}
